package com.example.materialdesigndemo.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.materialdesigndemo.R
import com.example.materialdesigndemo.entity.News

class NewsAdapter(newsList: List<News>) :
    RecyclerView.Adapter<NewsAdapter.ViewHolder>() {

    private val mNewsList = newsList

    private var newsItemClickListener: NewsItemClickListener? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder.from(parent)
    }

    override fun getItemCount(): Int = mNewsList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val news = mNewsList.get(position)
        holder.bind(news, position, newsItemClickListener)
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val newsTitle = itemView.findViewById<TextView>(R.id.newsTitleTv)
        val newsContent = itemView.findViewById<TextView>(R.id.newsContentTv)

        fun bind(
            item: News,
            position: Int,
            newsItemClickListener: NewsItemClickListener?
        ) {
            newsTitle.text = item.title
            newsContent.text = item.content
            itemView.setOnClickListener {
                newsItemClickListener?.onClick(position)
            }
        }

        companion object {
            fun from(parent: ViewGroup): ViewHolder {
                val view =
                    LayoutInflater.from(parent.context)
                        .inflate(R.layout.news_item_layout, parent, false)
                return ViewHolder(view)
            }

        }
    }

    fun setOnNewsItemClickListener(newsItemClickListener: NewsItemClickListener) {
        this.newsItemClickListener = newsItemClickListener
    }

    interface NewsItemClickListener {
        fun onClick(position: Int)
    }
}